package com.wanmait.community.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.community.entity.Para;
import com.wanmait.community.entity.User;
import com.wanmait.community.mapper.CarMapper;
import com.wanmait.community.mapper.ResidenceMapper;
import com.wanmait.community.mapper.UserMapper;
import com.wanmait.community.service.UserService;
import com.wanmait.community.util.AjaxResult;
import com.wanmait.community.util.JWTUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private CarMapper carMapper;
    @Resource
    private ResidenceMapper residenceMapper;
    @Value("${token.expireMinutes}")
    private int expireMinutes;
    @Value("${token.secret}")
    private String secret;

    @Override
    public AjaxResult detailUsers(Para user) {
        PageHelper.startPage(user.getPageNum(),user.getPageSize());
        LambdaQueryChainWrapper<User> wrapper = new LambdaQueryChainWrapper<User>(userMapper);
        List<User> userList = wrapper
                .like(StringUtils.isNotBlank(user.getIdentity()),User::getIdentity,user.getIdentity())
                .like(StringUtils.isNotBlank(user.getUserName()),User::getUserName,user.getUserName())
                .like(StringUtils.isNotBlank(user.getPhone()),User::getPhone,user.getPhone())
                .list();
        userList.forEach(user1 -> {
            user1.setCarCount(carMapper.countByUserId(user1.getId()));
            user1.setRoomCount(residenceMapper.countByUid(user1.getId()));
        });
        return AjaxResult.success(PageInfo.of(userList));
    }

    @Override
    public AjaxResult login(User user) {
        //首先检查用户名和密码是否合法
        if(user == null || StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getUserPass())){
            return AjaxResult.error(10001,"用户名或密码不能为空");
        }
        //根据用户名和密码查询用户
        User loginUser = userMapper.selectUserByUserNameAndUserPass(user);
        if(loginUser == null){
            return AjaxResult.error(10001,"用户名或密码错误");
        }
        //更新登录信息
        /*Admin updateAdmin = new Admin();
        updateAdmin.setId(loginAdmin.getId());
        updateAdmin.setLoginIp(admin.getLoginIp());
        updateAdmin.setLoginTime(new Date());
        updateAdmin.setLoginCount(loginAdmin.getLoginCount()+1);
        adminMapper.updateByPrimaryKeySelective(updateAdmin);*/
        //记录登录日志
       /* LoginLog loginLog = new LoginLog();
        loginLog.setAdminId(loginAdmin.getId());
        loginLog.setIp(admin.getLoginIp());
        loginLogMapper.insert(loginLog);*/
        //生成Token
        Map<String,String> claims = new HashMap<>();
        claims.put("userName",loginUser.getUserName());
        claims.put("phone",loginUser.getPhone());
        //签发对象,用户的id、用户名等固定的字符串  过期时间,分钟(默认60分钟)  密钥,可以是遗传很复杂的字符串,这里使用的是用户的密码  载荷,这里使用的是用户名和电话号码
        String token = JWTUtils.createToken(loginUser.getId().toString(),expireMinutes,loginUser.getUserPass(),claims);
        return AjaxResult.success()
                .put("userToken",token)
                .put("loginUser",loginUser)
                .put("identity",0);
    }

    @Override
    public User findById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }
}
